package ai.leinao.notify.dingtalk;

import ai.leinao.notify.core.AbstractNotifier;
import ai.leinao.notify.core.enums.NotifyType;
import ai.leinao.notify.core.template.TemplateRegistry;
import ai.leinao.notify.dingtalk.enums.DingTalkProviderEnum;
import ai.leinao.notify.dingtalk.utils.DingTalkRobotSignUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 钉钉机器人通知
 *
 * @author zhong.wang
 * @date 2025/7/11
 */
public class DingTalkRobotNotifier extends AbstractNotifier<DingTalkRobotTemplate> {
    /**
     * 通知id
     */
    private final String notifyId;

    /**
     * 钉钉机器人地址
     */
    private final String url;

    /**
     * 密钥
     */
    private final String secret;

    /**
     * 构造函数
     * @param notifyId
     * @param templateRegistry
     */
    public DingTalkRobotNotifier(String notifyId, String url, String secret, TemplateRegistry templateRegistry) {
        super(templateRegistry);
        this.url = url;
        this.secret = secret;
        this.notifyId = notifyId;
    }


    /**
     * 获取通知器ID
     *
     * @return 通知器ID
     */
    @Override
    public String getNotifyId() {
        return notifyId;
    }

    /**
     * 获取通知器类型
     *
     * @return 通知器类型
     * @see NotifyType
     */
    @Override
    public NotifyType getNotifyType() {
        return NotifyType.DING_TALK;
    }

    /**
     * 获取通知器供应商
     *
     * @return
     */
    @Override
    public String getProvider() {
        return DingTalkProviderEnum.DING_TALK_ROBOT.getType();
    }

    /**
     * 指定模板{@link Template}发送消息
     * <p>
     * 不同的供应商需实现不同的发送方式
     * <p>
     *
     * @param template 模板
     * @param context  上下文
     */
    @Override
    public void send(DingTalkRobotTemplate template, Map<String, Object> context) {
        JSONObject questBody = template.toJson(context);
        long timestamp = System.currentTimeMillis();
        String requestUrl = url + "&sign=" + DingTalkRobotSignUtil.getSign(timestamp, secret);
        requestUrl = requestUrl + "&timestamp=" + timestamp;
        HttpRequest request = HttpUtil.createRequest(Method.POST, requestUrl);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        request.addHeaders(headers);
        request.body(JSONUtil.toJsonStr(questBody));
        System.out.println(JSONUtil.toJsonStr(questBody));
        HttpResponse response = request.execute();
        System.out.println(response);
    }
}
